rm(list=ls())
gc()


library(dplyr)
library(ggplot2)
library(readr)
library(tidyr)
library(data.table)
library(wCorr)
library(patchwork)
library(xtable)


prec = rbindlist(lapply(c(2012,2016,2020), FUN = function(x){
  read_csv(paste0('precincts-',x,'.csv'))%>%
    mutate(year=x)%>%
    as.data.table
}),fill=T)%>%
  drop_na()

prec.cor = prec%>%
  group_by(year)%>%
  summarize(d.cor = round(weightedCorr(x=p.dem,y=dem.share,weights=n, method='Pearson'),2),
            r.cor  = round(weightedCorr(x=p.rep,y=rep.share,weights=n, method='Pearson'),2))



cty =  rbindlist(lapply(c(2012,2016,2020), FUN = function(x){
  read_csv(paste0('counties-',x,'.csv'))%>%
    mutate(year=x)%>%
    as.data.table
}),fill=T)%>%
  drop_na()

cty.cor = cty%>%
  group_by(year)%>%
  summarize(d.cor = round(weightedCorr(x=p.dem,y=dem.share,weights=n, method='Pearson'),2),
            r.cor  =round(weightedCorr(x=p.rep,y=rep.share,weights=n, method='Pearson'),2))

cor = merge(prec.cor,cty.cor,by='year')
print(xtable(cor),file = 'tables/TabS3.tex')
